package com.gainloop;

import java.util.ArrayList;
import java.util.LinkedList;

import org.alexd.jsonrpc.JSONRPCException;

import com.gainloop.Adapters.TagAdapter;
import com.gainloop.Api.ApiResponseArray;
import com.gainloop.Api.Categories;
import com.gainloop.Api.Entity.Category;
import com.gainloop.Api.Entity.WishEx;
import com.gainloop.Api.Wishes.SearchType;

import com.gainloop.Listeners.AutoCompListener;
import com.gainloop.Listeners.CategorySpinnerListener;
import com.gainloop.Listeners.TagsTextWatcher;
import com.gainloop.Listeners.tagButtonListener;
import com.gainloop.Utils.Constants;
import com.gainloop.Utils.ConvertUtils;
import com.gainloop.Utils.HorizontalListView;

import android.content.Intent;
import android.os.Bundle;

import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class GainSearch extends ActivityAbstract{
	String _chosenCategory;
	String _selectedUsersOption;
	private LinkedList<String> currentAddedTags; 
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gain_search);

		initHeader();
		headerTitle.setText(R.string.search);

		bindCategoriesSpinner();

		//adding tags
		currentAddedTags = new LinkedList<String>();

		AutoCompleteTextView tagsRow = (AutoCompleteTextView) findViewById(R.id.search_gain_autocomplete_tags);
		ArrayAdapter<String> tagsAdapter = new ArrayAdapter<String>(this, R.layout.list_item);
		tagsRow.setAdapter(tagsAdapter);

		//TextView addedTags = (TextView) findViewById(R.id.search_gain_added_tag);

		tagsRow.addTextChangedListener(new TagsTextWatcher(tagsAdapter));
		
		
		
		//Spinner usersSpinner=(Spinner)findViewById(R.id.search_gain_users_spinner);
		Button searchButton=(Button)findViewById(R.id.search_button);
		Button addTagButton = (Button) findViewById(R.id.search_gain_add_tag_button);
		final HorizontalListView addedTagsList = (HorizontalListView) findViewById(R.id.new_gain_added_tag_list); 
		bindUsersSpinner();
		
		TagAdapter  tagAdapter = new TagAdapter(currentAddedTags);
		addedTagsList.setAdapter(tagAdapter); 

		tagsRow.setOnItemClickListener(new AutoCompListener(currentAddedTags,tagAdapter,tagsRow));

		addedTagsList.setOnItemClickListener(new OnItemClickListener() {
			//here i will handle the removal of Tags
			@SuppressWarnings("rawtypes")
			@Override
			public void onItemClick(AdapterView parent, View v, int position, long id) {
				Log.v("remove tag in pos=",Integer.toString(position));

				currentAddedTags.remove(position);
				TagAdapter tagAdpter = (TagAdapter) addedTagsList.getAdapter();
				tagAdpter.notifyDataSetChanged();
			}
		}); 
		addTagButton.setOnClickListener(new tagButtonListener
				(tagsRow,getApplicationContext(),
						addedTagsList,currentAddedTags));

		searchButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				Long curCategoryId = getIntent().getExtras().getLong(Constants.CATEGORY_ID);
				ArrayList<WishEx> wishes=new ArrayList<WishEx>();
				SearchType type=SearchType.FRIENDS_ONLY;
				LinkedList<String> addedTags=currentAddedTags;
				Log.v("curCategoryId=",Long.toString(curCategoryId));
				if (isAllCategory(curCategoryId)){
					curCategoryId=null;
				}
				if (addedTags.isEmpty()){
					addedTags=null;
				}
				if (_selectedUsersOption.compareTo("Friends only")!=0){
					type=SearchType.NORMAL;
				}
				//try {
					/*
					if (addedTags==null&&curCategoryId==null){
						if (type==SearchType.FRIENDS_ONLY)
							wishes=Wishes.getInstance().getFriendsWishes(1);
						else
							wishes=Wishes.getInstance().getTopWishes(1);
					}
					else{
						wishes=Wishes.getInstance().search(curCategoryId,
								ConvertUtils.transformToTagList(currentAddedTags),
								SearchType.NORMAL, 1);
						
					}
					} catch (JSONRPCException e) {
						e.printStackTrace();
						throw new RuntimeException("error - getting search results");
					}*/
					Intent intent=new Intent(GainSearch.this,SearchResults.class)
					.putExtra(Constants.TAGS_STRING_ARR_KEY,addedTags)
					.putExtra(Constants.CATEGORY_ID, curCategoryId)
					.putExtra(Constants.SEARCH_TYPE, type);
					GainSearch.this.startActivity(intent);
					
					
				
				/*
				if (isAllCategory(curCategoryId)){
					if (currentAddedTags.isEmpty()){
						//no specific category and no tags are chosen
						//show top results.
						Toast.makeText(GainSearch.this, "top", Toast.LENGTH_SHORT).show();
						Intent intent=new Intent(GainSearch.this,SearchResults.class)
						.putExtra(Constants.listTypeParam,wishes);
						GainSearch.this.startActivity(intent);

					}
					else{
						//search by tags
						Toast.makeText(GainSearch.this, "tags", Toast.LENGTH_SHORT).show();

						Intent intent=new Intent(GainSearch.this,SearchResults.class)
						.putExtra(Constants.listTypeParam,ListType.SEARCH_TAGS);
						
						intent.putStringArrayListExtra(Constants.TAGS_STRING_ARR_KEY,new ArrayList<String>(currentAddedTags));
						GainSearch.this.startActivity(intent);
					}
				}
				else{
					//search by category
					if (currentAddedTags.isEmpty()){
						Toast.makeText(GainSearch.this, "category only", Toast.LENGTH_SHORT).show();
						
						Intent intent=new Intent(GainSearch.this,SearchResults.class)
						.putExtra(Constants.listTypeParam,ListType.SEARCH_CATEGORY);
						intent.putExtra(Constants.CATEGORY_ID, curCategoryId);
						GainSearch.this.startActivity(intent);
					}
					else{
						//search by category and tags
						Toast.makeText(GainSearch.this, "both", Toast.LENGTH_SHORT).show();

						Intent intent=new Intent(GainSearch.this,SearchResults.class)
						.putExtra(Constants.listTypeParam,ListType.SEARCH_BOTH);
						intent.putStringArrayListExtra(Constants.TAGS_STRING_ARR_KEY,new ArrayList<String>(currentAddedTags));
						intent.putExtra(Constants.CATEGORY_ID, curCategoryId);
						GainSearch.this.startActivity(intent);

					}
				}
				*/
			}
			
		});
	} 

	/**
	 * add to the spinner the all Categories from server. 
	 */
	private void bindUsersSpinner() {
		
		String[] usersSpinnerArr=new String[2];
		usersSpinnerArr[0]="All users";
		usersSpinnerArr[1]="Friends only";
		
		
		
		//adding spinner
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, usersSpinnerArr);   
		Spinner spinner = (Spinner) findViewById(R.id.search_gain_users_spinner);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent,
					View view, int pos, long id) {
				_selectedUsersOption = parent.getItemAtPosition(pos).toString();
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				_selectedUsersOption = parent.getItemAtPosition(0).toString();
				
			}
		});
		
		//adding All category as default.
		//getIntent().putExtra(Constants.CATEGORY_ID,Constants.ALL_CATEGORY_ID);
	}
	/**
	 * add to the spinner the all Categories from server. 
	 */
	private void bindCategoriesSpinner() {
		
		Categories categories = new Categories();
		ApiResponseArray<Category> resp = null;
		try {
			resp = categories.getAll();
		} catch (JSONRPCException e1) {
			e1.printStackTrace();
			Constants.declareInternalError(getApplicationContext());
			return;
		}
		ArrayList<Category> allCategories = null;
		if(resp==null){
			Constants.declareInternalError(getApplicationContext());
			Log.v("Categories resp=","null");
			return;
		}
		allCategories = resp.getData();

		String[] allCategoriesStrArr;

		Log.v("is allCategories null?=",Boolean.toString(allCategories==null));
		Log.v("return code=",Integer.toString(resp.getReturnCode()));

		if(allCategories==null){
			declareInternalError();
			Log.v("Categories fetch","Failed");
			return;
		}
		else{
			Log.v("allCategories size=",Integer.toString(allCategories.size()));
			allCategoriesStrArr = ConvertUtils.transformToStringArray(allCategories);
		}
		//adding the ALL Category
		allCategoriesStrArr = addAllCategory(allCategoriesStrArr);
		
		//adding spinner
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, allCategoriesStrArr);   
		Spinner spinner = (Spinner) findViewById(R.id.search_gain_category_spinner);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		CategorySpinnerListener spinnerListener=new CategorySpinnerListener(getIntent(),allCategories);
		spinner.setOnItemSelectedListener(spinnerListener);
		
		//adding All category as default.
		getIntent().putExtra(Constants.CATEGORY_ID,Constants.ALL_CATEGORY_ID);
	}
	
	/**
	 * Adding the All category to the string array
	 * @param allCategoriesStrArr 
	 * @return a array of string with the All category and all the given categories in allCategoriesStrArr
	 */
	private String[] addAllCategory(String[] allCategoriesStrArr) {
		String[] newStrArr = new String[allCategoriesStrArr.length+1];
		newStrArr[0] = Constants.ALL_CATEGORY;
		int i=1;
		for(String curCategory:allCategoriesStrArr){
			newStrArr[i]=curCategory;
			i++;
		}
		return newStrArr;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);

		MenuItem mi_profile = menu.findItem(R.id.menuProfile);
		mi_profile.setIntent(new Intent(this, Profile.class));

		MenuItem mi_newWish = menu.findItem(R.id.menuNewWish);
		mi_newWish.setIntent(new Intent(this, AddWish.class));

		MenuItem mi_home_gain = menu.findItem(R.id.menuHome); 
		mi_home_gain.setIntent(new Intent(this, Home.class));
		
		MenuItem mi_people = menu.findItem(R.id.menuPeople); 
		mi_people.setIntent(new Intent(this, People.class));


		menu.removeItem(R.id.menuSearch);
		return true;
	}

	/**
	 * Handling errors softly.
	 */
	private void declareInternalError(){
		Toast toast = Toast.makeText(GainSearch.this, R.string.internal_error, Toast.LENGTH_LONG);
		toast.show();
	}
	
	/**
	 * 
	 * @return true if the current category is ALL, false otherwise
	 */
	private boolean isAllCategory(Long curCategoryId){
		if(curCategoryId.compareTo(Constants.ALL_CATEGORY_ID)==0){
			return true;
		}
		return false;
	}


}
